package com.ccsu.joysport.util;

import io.jsonwebtoken.*;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String secretKey;

    public String generateToken(String account) {//生成token
        String token = Jwts.builder()
                .setSubject(account)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10小时
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        System.out.println("Generated Token: " + token);
        return token;
    }


    public boolean validateToken(String token) {//验证token
        System.out.println("Received Token: " + token);
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println("Parsed Claims: " + claims);
            return claims.getSubject() != null && !isTokenExpired(claims);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String parseToken(String token) {
        // 解析JWT token的逻辑
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
    }

    private boolean isTokenExpired(Claims claims) {//验证是否过期的方法
        boolean expired = claims.getExpiration().before(new Date());
        System.out.println("Token Expired: " + expired);
        return expired;
    }

    public String extractId(String token) {
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        return claims.getSubject(); // 返回subject字段存储的id
    }
}
